package cn.car.biz.impl;

import cn.car.biz.SysUserBiz;
import cn.car.domains.bo.QueryRoleBo;
import cn.car.domains.bo.QueryUserBo;
import cn.car.domains.entity.SysRoleEntity;
import cn.car.domains.entity.SysUserEntity;
import cn.car.domains.entity.SysUserRoleRelationEntity;
import cn.car.domains.vo.BasePage;
import cn.car.domains.vo.sysUser.*;
import cn.car.exception.CarAccessControlException;
import cn.car.mapper.SysUserRoleRelationMapper;
import cn.car.service.SysRoleService;
import cn.car.service.SysUserService;
import cn.car.service.config.SystemConfig;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SysUserBizImpl implements SysUserBiz {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SystemConfig systemConfig;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysUserRoleRelationMapper sysUserRoleRelationMapper;
    /**
     * 创建用户
     * 将前端传入的CreateUserReq转换为Entity并调用服务层保存
     */
    @Override
    public void createUser(CreateUserReq req) {

        // VO转换为Entity
        SysUserEntity userEntity = new SysUserEntity();
        BeanUtils.copyProperties(req, userEntity);

        // 调用服务层保存用户
        sysUserService.addUser(userEntity);
    }

    /**
     * 根据ID获取用户信息
     * 从服务层获取Entity后转换为响应VO
     */
    @Override
    public SysUserRes getUserById(Long id) {

        // 调用服务层查询
        SysUserEntity userEntity = sysUserService.getUserById(id);
        if (userEntity == null) {
            return null;
        }

        // Entity转换为响应VO
        SysUserRes sysUserRes = new SysUserRes();
        BeanUtils.copyProperties(userEntity, sysUserRes);

        //查询用户对应的角色

        //查询用户对应的权限
        return sysUserRes;
    }

    /**
     * 根据用户名获取用户信息
     */
    @Override
    public SysUserRes getUserByUsername(String username) {

        // 调��服务层查询
        SysUserEntity userEntity = sysUserService.getUserByUsername(username);
        if (userEntity == null) {
            return null;
        }

        // Entity转换为响应VO
        SysUserRes sysUserRes = new SysUserRes();
        BeanUtils.copyProperties(userEntity, sysUserRes);

        //查询用户对应的角色

        //查询用户对应的权限
        return sysUserRes;
    }

    /**
     * 更新用户信息
     */
    @Override
    public void updateUser(UpdateUserReq req) {

        // 检查用户是否存在
        SysUserEntity existingUser = sysUserService.getUserById(req.getId());
        if (existingUser == null) {
            throw CarAccessControlException.DATE_NOT_EXIST.newInstance("用户不存在");
        }

        // VO转换为Entity（只复制需要更新的字段）
        SysUserEntity updateEntity = new SysUserEntity();
        BeanUtils.copyProperties(req, updateEntity);

        // 调用服务层更新
        sysUserService.updateUser(updateEntity);
    }

    /**
     * 删除用户
     */
    @Override
    public void deleteUser(Long id) {

        // 检查用户是否存在
        SysUserEntity existingUser = sysUserService.getUserById(id);
        if (existingUser == null) {
            throw CarAccessControlException.DATE_NOT_EXIST.newInstance("用户不存在");
        }

        // 调用服务层删除
        sysUserService.deleteUser(id);
    }

    @Override
    public SysUserRes login(UserLoginReq req) {
        SysUserEntity userEntity = sysUserService.getUserByUsername(req.getUsername());
        if (!req.getPassword().equals(userEntity.getPassword())) {
            throw CarAccessControlException.PASSWORD_ERROR;
        }


        String token = generateToken(userEntity.getId());
        // Entity转换为响应VO
        SysUserRes sysUserRes = new SysUserRes();
        BeanUtils.copyProperties(userEntity, sysUserRes);
        sysUserRes.setToken(token);
        return sysUserRes;

    }

    private String generateToken(Long id) {
        // 过期时间：1小时（3600秒）
        long expireTime = System.currentTimeMillis() + 3600 * 1000;

        //  payload 中存放的自定义数据
        Map<String, Object> payload = new HashMap<>();
        payload.put("userId", id);      // 用户ID
        payload.put("exp", expireTime);   // 过期时间

        // 创建签名器（支持 HS256、HS384、HS512 等算法）
        JWTSigner signer = JWTSignerUtil.hs256(systemConfig.getJwtSecretKey().get().getBytes());

        // 生成 Token
        return JWTUtil.createToken(payload, signer);
    }

    /**
     * 分页查询用户信息
     * 使用PageHelper进行分页，支持用户名模糊查询
     */
    @Override
    public BasePage<SysUserRes> list(UserListReq req) {
        // 开启分页
        Page<Object> page = PageHelper.startPage(req.getPageNo(), req.getPageSize());

        QueryUserBo queryUserBo = new QueryUserBo();
        queryUserBo.setUsername(req.getUsername());
        // 调用服务层查询用户列表
        List<SysUserEntity> userEntityList = sysUserService.list(queryUserBo);

        // Entity列表转换为响应VO列表
        List<SysUserRes> userResList = userEntityList.stream()
                .map(entity -> {
                    SysUserRes sysUserRes = new SysUserRes();
                    BeanUtils.copyProperties(entity, sysUserRes);
                    // 不返回密码信息
                    sysUserRes.setPassword(null);
                    return sysUserRes;
                })
                .toList();

        // 构建分页信息
        return BasePage.generateResult(page.getPages(), page.getTotal(), userResList);
    }

    @Override
    public void addUserRole(AddUserRoleReq req) {
        SysUserEntity sysUserEntity = sysUserService.getUserById(req.getUserId());

        if (sysUserEntity == null){
            throw CarAccessControlException.DATE_EXIST.newInstance("用户不存在");
        }

        sysUserRoleRelationMapper.deleteByUserId(req.getUserId());

        QueryRoleBo queryRoleBo = new QueryRoleBo();
        queryRoleBo.setIds(req.getRoleIds());
        List<SysRoleEntity> list = sysRoleService.list(queryRoleBo);

        if (list.size() != req.getRoleIds().size()) {
            throw CarAccessControlException.DATE_NOT_EXIST.newInstance("有角色不存在");
        }

        List<SysUserRoleRelationEntity> sysUserRoleRelationEntityList = new ArrayList<>();

        for (Long roleId : req.getRoleIds()) {

            SysUserRoleRelationEntity sysUserRoleRelationEntity = new SysUserRoleRelationEntity();
            sysUserRoleRelationEntity.setUserId(req.getUserId());
            sysUserRoleRelationEntity.setRoleId(roleId);
            sysUserRoleRelationEntityList.add(sysUserRoleRelationEntity);
        }

        try {
            sysUserRoleRelationMapper.batchInsert(sysUserRoleRelationEntityList);
        } catch (DuplicateKeyException e) {
            log.warn("[用户添加添加角色] 目前已经有此角色 不需要重复添加");
        }
    }

}
